package common;

import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * test case
 */
public class TestCase {

    /**
     * Test Data Template
     */
    private static String  DATA_TEMPLATE="{\n" +
            " \"id\" : \"IDS60901\",\n" +
            " \"name\" : \"Adelaide (West Terrace / ngayirdapira)\",\n" +
            " \"state\" : \"SA\",\n" +
            " \"time_zone\" : \"CST\",\n" +
            " \"lat\": -34.9,\n" +
            " \"lon\": 138.6,\n" +
            " \"local_date_time\": \"15/04:00pm\",\n" +
            " \"local_date_time_full\": \"20230715160000\",\n" +
            " \"air_temp\": 13.3,\n" +
            "\"apparent_t\": 9.5,\n" +
            " \"cloud\": \"Partly cloudy\",\n" +
            " \"dewpt\": 5.7,\n" +
            " \"press\": 1023.9,\n" +
            " \"rel_hum\": 60,\n" +
            " \"wind_dir\": \"S\",\n" +
            " \"wind_spd_kmh\": 15,\n" +
            " \"wind_spd_kt\": 8\n" +
            "}";


    public static void main(String[] args) throws IOException, InterruptedException {
        sendMethodData();
        sendEmptyData();
        // sendRangeData(30);

        sendRangeDataCluster(50);

        sendGetClient();
    }


    // send empty data
    public static void sendEmptyData() throws IOException {
        HttpUtils.sendPutRequest("http://localhost:4567","");
    }


    // Sending data with a random number of entries
    public static void sendRangeData(int size) throws IOException {
        JSONObject jsonObject = JSONObject.parseObject(DATA_TEMPLATE);
        for (int i = 0; i < size; i++) {
            jsonObject.put("id",jsonObject.getString("id")+(i+1));
            // Random timestamp, simulating data requests with different timestamps, while testing the removal of the last 20 requests
            jsonObject.put("timestamp",System.currentTimeMillis()+(int)((Math.random()*10001+10000)));
            HttpUtils.sendPutRequest("http://localhost:4567",jsonObject.toJSONString());
        }
    }


    // Sending non get/put requests
    public static void sendMethodData() throws IOException {
        HashMap resultMap = HttpUtils.sendPostRequest("http://localhost:4567","{}");
    }

    public static void sendGetClient() throws IOException {
        HashMap resultMap = HttpUtils.sendGetRequest("http://localhost:4567");
        System.out.println("Obtained weather information\n" +
                "\n："+resultMap.get("result"));
    }



    // Simulate cluster sending data
    public static void sendRangeDataCluster (int size) throws IOException, InterruptedException {
        JSONObject jsonObject = JSONObject.parseObject(DATA_TEMPLATE);
        String id=jsonObject.getString("id");
        ExecutorService executorService=Executors.newFixedThreadPool(20);
        CountDownLatch downLatch=new CountDownLatch(size);
        for (int i = 0; i < size; i++) {
            JSONObject sendData = JSONObject.parseObject(jsonObject.toJSONString());
            sendData.remove(id);
            sendData.put("id",id+(i+1));
            // Simulate cluster requests
            executorService.execute(new SendTask(i,sendData,downLatch));
        }
        // Waiting for all cluster data to be sent
        downLatch.await();
        System.out.println("All data sent completed\n" +
                "\n");
        executorService.shutdown();
    }


    /**
     * Send cluster data task
     */
    public static class SendTask implements Runnable{

        private int i;
        private JSONObject jsonObject;
        CountDownLatch downLatch;
        public SendTask(int i, JSONObject jsonObject,CountDownLatch downLatch) {
            this.i = i;
            this.jsonObject = jsonObject;
            this.downLatch=downLatch;
        }

        @Override
        public void run() {
            try {
                // Random timestamp, simulating data requests with different timestamps
                jsonObject.put("timestamp",System.currentTimeMillis()+(int)((Math.random()*10001+10000)));
                System.out.println("node"+Thread.currentThread().getName()+"send data："+jsonObject.toJSONString());
                HttpUtils.sendPutRequest("http://localhost:4567",jsonObject.toJSONString());
            } catch (IOException e) {
               e.printStackTrace();
            }finally {
                downLatch.countDown();
                System.out.println("node"+Thread.currentThread().getName()+"Sending data completed\n" +
                        "\n");
            }
        }
    }
}
